package com.cipe.cmrs.util;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.ClassEditor;

public class CustomTimestampEditor extends ClassEditor {

	protected Logger logger = LoggerFactory.getLogger(CustomTimestampEditor.class);

	private final SimpleDateFormat format;

	public CustomTimestampEditor(String format) {
		this.format = new SimpleDateFormat(format);
		this.format.setLenient(true);
	}

	public void setAsText(String text) throws IllegalArgumentException {

		if (StringUtils.isBlank(text)) {

			setValue(null);

		} else {

			try {

				logger.debug("Parsing date: " + text);

				Date date = format.parse(text);

				logger.debug("Parsed Date: " + date);

				Timestamp stamp = new Timestamp(date.getTime());

				logger.debug("Parsed Timestamp: " + stamp);

				setValue(stamp);

			} catch (Exception ex) {
				throw new IllegalArgumentException("Value could not be converted: " + text);
			}
		}
	}

	public String getAsText() {

		if (getValue() == null) {
			return null;
		} else {

			return format.format(getValue());
		}
	}
}
